
_ = require 'underscore'
fsp = require '../bin/libs/fs-promises'
Q = require 'q'
path = require 'path'
crypto = require 'crypto'

###
拦截器
###
module.exports= (app)->

  SALT_COOKIE = "remember_me&&!!"

  isAdmin = (url) ->
    new RegExp(/^\/admin*/).test(url)

  noLoginUrl = [
      /^\/login*/,  /^\/logout*/, /^\/register*/, /.*\/appdowload\?*/, /\/apps\/img*/
      /^\/admin\/login*/,  /^\/admin\/logout*/, /^\/admin\/register*/,
      /^\/resetpwd*/,  /^\/validateCode*/,/^\/sendEmailCode*/,/^\/validateEmailCode*/,/^\/updatePassword*/

      ]

  _pattenUrl = (url) ->
    isPatten = false
    _.each noLoginUrl, (each) ->
      isPatten = true if new RegExp(each).test(url)
    isPatten

  #生成密文，默认HMAC函数是sha1算法
  _signedCookies = (txt, salt, cb) ->
    txt = txt || ""
    txt = txt.toString()
    crypto.pbkdf2 txt, salt, 1024, 8, (err, hash) ->
      cb err, hash.toString('hex'), salt

  #验证cookie
  _verifyRememberMe = (cookies) ->
    new Promise (resolve, reject) ->
      remember_me = cookies.remember_me
      if remember_me
        remember_me = JSON.parse(remember_me)
        _signedCookies remember_me.name, SALT_COOKIE, (err, hash) ->
          return resolve(false) if err
          return resolve(false) if hash != remember_me.sign
          resolve(true)
       else
         resolve(false)

  #session 当前用户会话
  #拦截所有非静态资源的路由
  app.use (req, res, next) ->
    url = req.originalUrl
    if _pattenUrl url
      next()
    else if req.session and req.session.user
      #分两块走
      if req.session.user.role == "admin"
        console.log isAdmin(req.originalUrl)
        if isAdmin(req.originalUrl) then next() else res.redirect '/admin/login'
      else
        if !isAdmin(req.originalUrl) then next() else res.redirect '/login'
    else
      _verifyRememberMe req.cookies
      .then (result) ->
        if result
          #TODO 7天自动登录
        else
          res.redirect '/login'
